package com.zhenhunfan.io.model.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * <p>Title: NettyServer</p>
 * <p>Description: netty服务端</p>
 *
 * @author zhenhunfan
 * @version 1.0.0
 * @date 2021/4/6
 */
public class NettyServer {
    int port = 8888;

    public NettyServer(int port) {
        this.port = port;
    }

    public void serverStart() {
        //类似于selector的线程池，只负责连接
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        //读写操作的线程池，IO处理
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        //服务器启动时的初始化配置
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class) //指定通道类型
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    //连接后的处理，在通道上加一个处理器
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new Handler());
                    }
                });
        try {
            ChannelFuture f = b.bind(port).sync();
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }

    }
}
